package cn.ilovese.collect.serviceimpl.report;

import cn.ilovese.collect.controller.socket.WebSocketServer;
import cn.ilovese.collect.datamapper.report.*;
import cn.ilovese.collect.datamapper.task.TaskMapper;
import cn.ilovese.collect.datamapper.user.ActivityMapper;
import cn.ilovese.collect.datamapper.user.UserMapper;
import cn.ilovese.collect.datamapper.workermessage.WorkerMessageMapper;
import cn.ilovese.collect.po.report.*;
import cn.ilovese.collect.po.task.Task;
import cn.ilovese.collect.po.user.Activity;
import cn.ilovese.collect.po.user.User;
import cn.ilovese.collect.po.workermessage.WorkerMessage;
import cn.ilovese.collect.service.report.ScoreService;
import cn.ilovese.collect.serviceimpl.report.similaritystrategy.SimHashStrategy;
import cn.ilovese.collect.util.Constant;
import cn.ilovese.collect.vo.NullVO;
import cn.ilovese.collect.po.follow.Follow;
import cn.ilovese.collect.po.similarity.PicSimilarity;
import cn.ilovese.collect.datamapper.follow.FollowMapper;
import cn.ilovese.collect.vo.OthersEvaluateAbilityVO;
import cn.ilovese.collect.vo.ResultVO;
import cn.ilovese.collect.vo.report.ComprehensiveScoreVO;
import cn.ilovese.collect.vo.report.ScoreAllVO;
import cn.ilovese.collect.vo.report.ScoreVO;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import cn.ilovese.collect.vo.report.*;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.corpus.tag.Nature;
import com.hankcs.hanlp.seg.common.Term;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@CacheConfig(cacheNames = "score",cacheManager = "cacheManager")
public class ScoreServiceImpl implements ScoreService {
    @Resource
    ScoreSimilarityMapper scoreSimilarityMapper;

    @Resource
    ScoreMapper scoreMapper;

    @Resource
    BossScoreMapper bossScoreMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    WorkerMessageMapper workerMessageMapper;

    @Resource
    ReportMapper reportMapper;

    @Resource
    TaskMapper taskMapper;

    @Resource
    LikeMapper likeMapper;

    @Resource
    SimHashStrategy simHashStrategy;

    @Resource
    ActivityMapper activityMapper;

    @Resource
    FollowMapper followMapper;


    @Override
    public ResultVO<ScoreVO> postScoreOfReport(ScoreVO scoreVO) {
        Score record = new Score(scoreVO);
        int id = scoreMapper.insert(record);
        if(reportMapper.selectByPrimaryKey(record.getReportId()).getUserId()!=record.getUserId()) {
            WorkerMessage message = new WorkerMessage();
            Report nowReport = reportMapper.selectByPrimaryKey(record.getReportId());
            message.setCooReportId(0);
            message.setMessageType(0);
            message.setReportId(record.getReportId());
            message.setFromRole(1);
            message.setSubmitTime(new Date());
            message.setFromUserId(record.getUserId());
            message.setToWorkerId(nowReport.getUserId());
            message.setStatus(0);
            message.setTaskId(nowReport.getTaskId());
            message.setTaskName(taskMapper.selectByPrimaryKey(nowReport.getTaskId()).getTaskName());
            int messageId = workerMessageMapper.insert(message);
            WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0, message.getToWorkerId()), message.getToWorkerId());
        }
        if(id < 1)
            return new ResultVO<>(Constant.REQUEST_FAIL, "插入失败");
        else{
            Date nowTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String nowDate = sdf.format(nowTime);
            Activity loginRecord=activityMapper.selectByUserIdAndLoginDate(scoreVO.getUserId(),nowDate);
            activityMapper.increaseActivityByUserid(scoreVO.getUserId(),2,nowDate);
            ScoreVO res = new ScoreVO(record);
            //计算和其他报告的相似度
            //因为先提交的评论的id比较小，所以考虑用first存现在的id，然后用second存之前的id
            Integer reportId = record.getReportId();
            List<Score> scores = scoreMapper.selectByReportId(reportId);
            String content = record.getDescription();
            Integer firstId = record.getId();
            System.out.println("firstId:" + record.getId());
            for(Score score: scores){
                System.out.println("secondId:" + score.getId());
                if(score.getId().equals(record.getId()))
                    continue;
                String temp = score.getDescription();
                Double sim = simHashStrategy.TextSimilarity(content,temp);
                ScoreSimilarity scoreSimilarity = new ScoreSimilarity();
                scoreSimilarity.setFirstId(firstId);
                scoreSimilarity.setSecondId(score.getId());
                scoreSimilarity.setSimilarity(sim);
                int success = scoreSimilarityMapper.insert(scoreSimilarity);
                if(success < 1)
                    return new ResultVO<>(Constant.REQUEST_FAIL,"插入相似度时失败", res);
            }
            return new ResultVO<>(Constant.REQUEST_SUCCESS,"插入成功", res);
        }
    }

    @Override
    public ResultVO<NullVO> deleteScoreOfReport(Integer commentid) {
        workerMessageMapper.deleteByFromUserIdAndReportIdAndWorker(scoreMapper.selectByPrimaryKey(commentid).getUserId(),scoreMapper.selectByPrimaryKey(commentid).getReportId());
        int userid=reportMapper.selectByPrimaryKey(scoreMapper.selectByPrimaryKey(commentid).getReportId()).getUserId();
        int id = scoreMapper.deleteByPrimaryKey(commentid);
        WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0,userid),userid);
        System.out.println("id:" + id);
        if(id < 1)
            return new ResultVO<>(Constant.REQUEST_FAIL,"删除失败");
        return new ResultVO<>(Constant.REQUEST_SUCCESS, "删除成功");
    }

    @Override
    public ResultVO<ScoreVO> getMyScoreOfReport(Integer reportid, Integer workerid) {
        Score score = scoreMapper.selectByWorkerAndReport(reportid,workerid);
        if(score == null)
            return new ResultVO<>(Constant.REQUEST_FAIL,"获取评价详细信息失败");
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取评价详细信息成功", new ScoreVO(score));
    }

    @Override
    public ResultVO<ScoreVO> updateScoreOfReport(ScoreVO scoreVO) {
        int id = scoreVO.getId();
        System.out.println(id);
        if(scoreMapper.selectByPrimaryKey(id) == null)
            return new ResultVO<>(Constant.REQUEST_FAIL, "不存在此评价");
        Score newScore = new Score(scoreVO);
        newScore.setId(id);
        int res = scoreMapper.updateByPrimaryKey(newScore);
        if(reportMapper.selectByPrimaryKey(scoreVO.getReportId()).getUserId()!=scoreVO.getUserId()) {
            workerMessageMapper.deleteByFromUserIdAndReportIdAndWorker(scoreVO.getUserId(), scoreVO.getReportId());
            WorkerMessage message = new WorkerMessage();
            Report nowReport = reportMapper.selectByPrimaryKey(scoreVO.getReportId());
            message.setCooReportId(0);
            message.setMessageType(0);
            message.setReportId(scoreVO.getReportId());
            message.setFromRole(1);
            message.setSubmitTime(new Date());
            message.setFromUserId(scoreVO.getUserId());
            message.setToWorkerId(nowReport.getUserId());
            message.setStatus(0);
            message.setTaskId(nowReport.getTaskId());
            message.setTaskName(taskMapper.selectByPrimaryKey(nowReport.getTaskId()).getTaskName());
            int messageId = workerMessageMapper.insert(message);
            WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0, message.getToWorkerId()), message.getToWorkerId());
        }
        if(res == 0)
            return new ResultVO<>(Constant.REQUEST_FAIL, "更新失败");
        Date nowTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sdf.format(nowTime);
        Activity loginRecord=activityMapper.selectByUserIdAndLoginDate(scoreVO.getUserId(),nowDate);
        activityMapper.increaseActivityByUserid(scoreVO.getUserId(),2,nowDate);
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"更新成功",new ScoreVO(newScore));
    }

    @Override
    public ResultVO<ScoreAllVO> getScoresOfReport(Integer reportid,Integer loginid) {
        List<Score> temp = scoreMapper.selectByReportId(reportid);
        if(temp.size() == 0)
            return new ResultVO<>(Constant.REQUEST_FAIL,"当前该报告没有人评价");
        List<ScoreVO> res = new ArrayList<>();
        for(Score score: temp){
            ScoreVO newTemp=new ScoreVO(score);
            newTemp.setUsername(userMapper.selectByPrimaryKey(newTemp.getUserId()).getUsername());
            if(likeMapper.selectByScoreIdAndUserId(newTemp.getId(),loginid)==null) {
                newTemp.setIsLoginUserLiked(0);
            }else
                newTemp.setIsLoginUserLiked(1);
            if(likeMapper.selectByScoreIdAndUserId(newTemp.getId(),reportMapper.selectByPrimaryKey(reportid).getUserId())==null)
                newTemp.setIsReportOwnerLiked(0);
            else
                newTemp.setIsReportOwnerLiked(1);
            newTemp.setLikeNum(likeMapper.countByScoreId(newTemp.getId()));
            res.add(newTemp);
        }
        Float sum= Float.valueOf(0);
        for(int i=0;i<res.size();i++){
            sum=sum+res.get(i).getScore();
        }
        ScoreAllVO returnData=new ScoreAllVO();
        returnData.setScore(sum/res.size());
        returnData.setComments(res);
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取报告所有评价成功",returnData);
    }

    @Override
    public ResultVO<ComprehensiveScoreVO> getCompreScoreOfReport(Integer reportid) {
        /*List<ComprehensiveScoreVO> temp = scoreMapper.selectByReportId(reportid);
        if(temp.size() == 0)
            return new ResultVO<>(Constant.REQUEST_FAIL,"当前该报告没有人评价");
        List<ScoreVO> res = new ArrayList<>();
        for(Score score: temp){
            res.add(new ScoreVO(score));
        }
        Float sum= Float.valueOf(0);
        for(int i=0;i<res.size();i++){
            sum=sum+res.get(i).getScore();
        }
        res.get(0).setComprehensiveScore(sum/res.size());
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取报告所有评价成功",res);

         */
        return null;
    }

    @Override
    public ResultVO<NullVO> likeScore(Integer userid, Integer commentid) {
        Like record=new Like();
        record.setUserId(userid);
        record.setScoreId(commentid);
        if(userid==reportMapper.selectByPrimaryKey(scoreMapper.selectByPrimaryKey(commentid).getReportId()).getUserId())
            record.setLikeType(1);
        else {
            String userType = userMapper.selectByPrimaryKey(userid).getRole();
            if(userType.equals("boss"))
                record.setLikeType(2);
            else
                record.setLikeType(0);
        }
        int id=likeMapper.insert(record);
        if(userid!=scoreMapper.selectByPrimaryKey(commentid).getUserId()) {
            WorkerMessage message = new WorkerMessage();
            Report nowReport = reportMapper.selectByPrimaryKey(scoreMapper.selectByPrimaryKey(record.getScoreId()).getReportId());
            message.setCooReportId(0);
            message.setMessageType(3 + record.getLikeType());
            message.setReportId(nowReport.getId());
            if (message.getMessageType() == 5)
                message.setFromRole(0);
            else
                message.setFromRole(1);
            message.setSubmitTime(new Date());
            message.setFromUserId(userid);
            //System.out.println("hhhhhhh"+scoreMapper.selectByPrimaryKey(commentid).getUserId());
            message.setToWorkerId(scoreMapper.selectByPrimaryKey(commentid).getUserId());
            message.setStatus(0);
            message.setTaskId(nowReport.getTaskId());
            message.setTaskName(taskMapper.selectByPrimaryKey(nowReport.getTaskId()).getTaskName());
            int messageId = workerMessageMapper.insert(message);
            WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0, message.getToWorkerId()), message.getToWorkerId());
        }
        if(id < 1)
            return new ResultVO<>(Constant.REQUEST_FAIL, "点赞失败");
        else{
            return new ResultVO<>(Constant.REQUEST_SUCCESS,"点赞成功",new NullVO());
        }
    }

    @Override
    public ResultVO<NullVO> unlikeScore(Integer userid, Integer commentid) {
        workerMessageMapper.deleteByFromUserIdAndReportIdAndLike(userid,scoreMapper.selectByPrimaryKey(commentid).getUserId(),scoreMapper.selectByPrimaryKey(commentid).getReportId());
        int touserid=scoreMapper.selectByPrimaryKey(commentid).getUserId();
        int id=likeMapper.deleteByUserIdAndScoreId(userid,commentid);
        WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0,touserid),touserid);
        if(id < 1)
            return new ResultVO<>(Constant.REQUEST_FAIL,"取消点赞失败");
        return new ResultVO<>(Constant.REQUEST_SUCCESS, "取消点赞成功");
    }

    @Override
    public ResultVO<BossScoreVO> postBossScoreOfReport(BossScoreVO bossScoreVO) {
        BossScore record = new BossScore(bossScoreVO);
        int id = bossScoreMapper.insert(record);
        WorkerMessage message = new WorkerMessage();
        Report nowReport = reportMapper.selectByPrimaryKey(record.getReportId());
        message.setCooReportId(0);
        message.setMessageType(1);
        message.setReportId(record.getReportId());
        message.setFromRole(0);
        message.setSubmitTime(new Date());
        message.setFromUserId(
                taskMapper.selectByPrimaryKey(
                        nowReport.getTaskId()).getUserId());
        message.setToWorkerId(nowReport.getUserId());
        message.setStatus(0);
        message.setTaskId(nowReport.getTaskId());
        message.setTaskName(taskMapper.selectByPrimaryKey(nowReport.getTaskId()).getTaskName());
        int messageId = workerMessageMapper.insert(message);
        WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0, message.getToWorkerId()), message.getToWorkerId());
        if(id < 1)
            return new ResultVO<>(Constant.REQUEST_FAIL, "插入失败");
        else{
            BossScoreVO res = new BossScoreVO(record);
            return new ResultVO<>(Constant.REQUEST_SUCCESS,"插入成功",res);
        }
    }

    @Override
    public ResultVO<NullVO> deleteBossScoreOfReport(Integer commentid) {
        System.out.println(commentid);
        int reportId=bossScoreMapper.selectByPrimaryKey(commentid).getReportId();
        workerMessageMapper.deleteByFromUserIdAndReportIdAndBoss(taskMapper.selectByPrimaryKey(
                reportMapper.selectByPrimaryKey(
                        reportId).getTaskId()).getUserId(),reportId);
        int userid=reportMapper.selectByPrimaryKey(bossScoreMapper.selectByPrimaryKey(commentid).getReportId()).getUserId();
        int id = bossScoreMapper.deleteByPrimaryKey(commentid);
        WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0,userid),userid);
        System.out.println("id:" + id);
        if(id < 1)
            return new ResultVO<>(Constant.REQUEST_FAIL,"删除失败");
        return new ResultVO<>(Constant.REQUEST_SUCCESS, "删除成功");
    }

    @Override
    public ResultVO<BossScoreVO> getBossScoreOfReport(Integer reportid) {
        BossScore bossScore = bossScoreMapper.selectByReport(reportid);
        if(bossScore == null)
            return new ResultVO<>(Constant.REQUEST_FAIL,"暂未评价");
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取发包方评价详细信息成功", new BossScoreVO(bossScore));
    }

    @Override
    public ResultVO<BossScoreVO> updateBossScoreOfReport(BossScoreVO bossScoreVO) {
        int id = bossScoreVO.getId();
        System.out.println(id);
        if(bossScoreMapper.selectByPrimaryKey(id) == null)
            return new ResultVO<>(Constant.REQUEST_FAIL, "不存在此评价");
        BossScore newScore = new BossScore(bossScoreVO);
        newScore.setId(id);
        int res = bossScoreMapper.updateByPrimaryKey(newScore);
        int fromUserId=taskMapper.selectByPrimaryKey(
                reportMapper.selectByPrimaryKey(bossScoreVO.getReportId()).getTaskId()).getUserId();
        workerMessageMapper.deleteByFromUserIdAndReportIdAndBoss(fromUserId, bossScoreVO.getReportId());
        WorkerMessage message = new WorkerMessage();
        Report nowReport = reportMapper.selectByPrimaryKey(bossScoreVO.getReportId());
        message.setCooReportId(0);
        message.setMessageType(1);
        message.setReportId(bossScoreVO.getReportId());
        message.setFromRole(0);
        message.setSubmitTime(new Date());
        message.setFromUserId(fromUserId);
        message.setToWorkerId(nowReport.getUserId());
        message.setStatus(0);
        message.setTaskId(nowReport.getTaskId());
        message.setTaskName(taskMapper.selectByPrimaryKey(nowReport.getTaskId()).getTaskName());
        int messageId = workerMessageMapper.insert(message);
        WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0, message.getToWorkerId()), message.getToWorkerId());
        if(res == 0)
            return new ResultVO<>(Constant.REQUEST_FAIL, "更新失败");
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"更新成功",new BossScoreVO(newScore));
    }

    //返回一个用户打过分的所有报告
    @Override
    public ResultVO<List<ReportVO>> getScoredReports(Integer userId){
        List<Score> scores=scoreMapper.selectByWorker(userId);
        List<ReportVO>res=new ArrayList<>();
        for(Score score:scores){
            Integer reportId=score.getReportId();
            Report report=reportMapper.selectByPrimaryKey(reportId);
            res.add(new ReportVO(report));
        }
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取用户所评论过的所有报告成功！",res);
    }

    //返回”关键词“的形式，类似词云，直接分析他点评过的报告的关键词,一个“词，词频”的列表
    //TODO:商榷：是返回点评过的报告的关键词 还是返回点评本身的关键词？暂时采用前者
    public HashMap<String,Integer> getCommentKeyWords(Integer userId){
        //List<WorkerScoreKeywordsVO>res=new ArrayList<>();
        HashMap<String,Integer> res=new HashMap<>();
        String src="";
        List<Score> scores=scoreMapper.selectByWorker(userId);
        for(Score score:scores){
            Integer reportId=score.getReportId();
            Report report=reportMapper.selectByPrimaryKey(reportId);
            src+=report.getDescription()+report.getSteps()+report.getDeviceInfo();
        }
        List<Term> words= HanLP.segment(src);//分词并遍历
        HashMap<String,Integer> hashMap=new HashMap<>();
        for(Term tm:words){
            if(!tm.nature.equals(Nature.v)&&!tm.nature.equals(Nature.ad)&&!tm.nature.equals(Nature.a)&&!tm.nature.equals(Nature.n)){
                continue;
            }
            if(tm.word.length()==1)
                continue;
            String word=tm.word;
            if(hashMap.containsKey(word)){
                hashMap.put(word,hashMap.get(word)+1);
            }
            else hashMap.put(word,1);
        }
        return hashMap;
//        Iterator<java.util.Map.Entry<String,Integer>> iterator = hashMap.entrySet().iterator();
//        while (iterator.hasNext()) {
//            java.util.Map.Entry<String,Integer> entry = iterator.next();
//            WorkerScoreKeywordsVO workerScoreKeywordsVO=new WorkerScoreKeywordsVO(entry.getKey(),entry.getValue());
//            res.add(workerScoreKeywordsVO);
//        }
//        return res;
    }

    //获取用户最爱评价的工人列表
    public List<ScoreFavourWorkerVO> getFavoriteWorkersByID(Integer userId){
        List<ScoreFavourWorkerVO> res=new ArrayList<>();
        List<Score> scores=scoreMapper.selectByWorker(userId);
        HashMap<Integer,Integer> hasAppeared=new HashMap<>();
        Integer num=0;
        for(Score score:scores){
            Report report=reportMapper.selectByPrimaryKey(score.getReportId());
            Integer workerId=report.getUserId();
            if(hasAppeared.containsKey(workerId)){
                Integer id=hasAppeared.get(workerId);
                ScoreFavourWorkerVO favoriteWorkerVO=res.get(id);
                favoriteWorkerVO.setEvaluateNum(favoriteWorkerVO.getEvaluateNum()+1);
                res.set(id,favoriteWorkerVO);
            }
            else{
                ScoreFavourWorkerVO favoriteWorkerVO=new ScoreFavourWorkerVO();
                favoriteWorkerVO.setEvaluateNum(1);
                User user=userMapper.selectByPrimaryKey(workerId);
                favoriteWorkerVO.setId(user.getId());
                favoriteWorkerVO.setUsername(user.getUsername());
                res.add(favoriteWorkerVO);
                hasAppeared.put(workerId,num);
                num++;
            }
        }
        return res;
    }

    List<ScoreBiasVO> getScoreBias(Integer userId){
        List<Score> scores=scoreMapper.selectByWorker(userId);
        List<ScoreBiasVO>res=new ArrayList<>();
        for(Score score:scores){
            Integer reportId=score.getReportId();
            Float tot=Float.valueOf(0);
            Integer num=0;
            List<Score> temp = scoreMapper.selectByReportId(reportId);
            for(Score score0: temp){
                tot+=score0.getScore();
                num++;
            }
            tot/=num;
            ScoreBiasVO scoreBiasVO=new ScoreBiasVO();
            scoreBiasVO.setAverageScore(tot);
            scoreBiasVO.setScore(score.getScore());
            scoreBiasVO.setBias(score.getScore()-tot);
            scoreBiasVO.setReportid(reportId);
            res.add(scoreBiasVO);
        }
        return res;
    }

    @Override
    public ResultVO<ScoreAbilityVO> getGeneralScoreAbility(Integer userId) {
        ScoreAbilityVO res=new ScoreAbilityVO();
        res.setPlagiarismScore(getPlagiarismScore(userId));
        res.setWordFreq(getCommentKeyWords(userId));
        res.setFavoriteWorkers(getFavoriteWorkersByID(userId));
        res.setAccuracyList(getScoreBias(userId));
        Double acc=0.0;
        for(ScoreBiasVO scoreBiasVO:res.getAccuracyList()){
            acc+=Math.abs(scoreBiasVO.getBias());
        }
        acc/=5;
        if(acc==0)
            res.setAccuracyScore(1.0);
        else res.setAccuracyScore(1.0-acc/res.getAccuracyList().size());
        List<Score> scores=scoreMapper.selectByWorker(userId);
        res.setAllNum(scores.size());
        Integer validNum=0;
        for(Score score:scores){
            Report report=reportMapper.selectByPrimaryKey(score.getReportId());
            Task task=taskMapper.selectByPrimaryKey(report.getTaskId());
            Like like=likeMapper.selectByScoreIdAndUserId(score.getId(),task.getUserId());
            if(like!=null)
                validNum++;
            //看看是不是创作者觉得很赞
            else{
                Integer authorId = report.getUserId();
                like = likeMapper.selectByScoreIdAndUserId(score.getId(),authorId);
                if(like != null)
                    validNum++;
            }
        }
        res.setValidNum(validNum);
        Double general = 0.0;
        if(res.getAllNum() != 0)
            general=res.getPlagiarismScore()+res.getAccuracyScore()+(1.0*res.getValidNum()/res.getAllNum());
        res.setGeneralScore(general/3);
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取用户评价综合能力数据成功！",res);
    }

    @Override
    public ResultVO<OthersEvaluateAbilityVO> getOthersEvaluateAbility(Integer workerid) {
        List<Report> allReportByUser=reportMapper.selectByUser(workerid);
        Integer bossEvaluationNum=0;
        Integer workerEvaluationNum=0;
        Float workerEvaluationScore=0.0F;
        List<Float> workerScores=new ArrayList<>();

        Float[] bossMetrics=new Float[5];
        for(int i=0;i<5;i++){
            bossMetrics[i]=0.0F;
        }
        String allComments="";

        //词频使用HashMap进行
        HashMap<String, Integer> commentWordFreq = new HashMap<>();

        for(Report temp:allReportByUser) {
            BossScore bossScoreTemp=bossScoreMapper.selectByReport(temp.getId());

            if(bossScoreTemp!=null){
                bossEvaluationNum = bossEvaluationNum + 1;
                bossMetrics[0]+=getScoreFloat(bossScoreTemp.getTaskFit());
                bossMetrics[1]+=getScoreFloat(bossScoreTemp.getReality());
                bossMetrics[2]+=getScoreFloat(bossScoreTemp.getDefectImportance());
                bossMetrics[3]+=getScoreFloat(bossScoreTemp.getRecurrence());
                bossMetrics[4]+=getScoreFloat(bossScoreTemp.getTotalQuality());
            }

            List<Score> workerScoreList=scoreMapper.selectByReportId(temp.getId());
            if(workerScoreList!=null) {
                for (Score workerScoreTemp : workerScoreList) {
                    //先分词然后计算词频
                    allComments=allComments+workerScoreTemp.getDescription()+"; ";

                    workerEvaluationNum = workerEvaluationNum + 1;
                    workerScores.add(workerScoreTemp.getScore());
                    workerEvaluationScore = workerEvaluationScore + workerScoreTemp.getScore();
                }
            }
        }

        //处理评分数据
        workerEvaluationScore=workerEvaluationScore/workerEvaluationNum;
        for(int i=0;i<5;i++){
            bossMetrics[i]=bossMetrics[i]/bossEvaluationNum;
        }

        List<Term> words = HanLP.segment(allComments);
        //对词频进行统计
        for (Term tm : words) {
            if (!tm.nature.equals(Nature.v) && !tm.nature.equals(Nature.ad) && !tm.nature.equals(Nature.a) && !tm.nature.equals(Nature.n)) {
                continue;
            }
            String word = tm.word;
            if(word.length()>1) {
                if (commentWordFreq.containsKey(word)) {
                    commentWordFreq.put(word, commentWordFreq.get(word) + 1);
                } else
                    commentWordFreq.put(word, 1);
            }
        }
        OthersEvaluateAbilityVO res=new OthersEvaluateAbilityVO();
        res.setBossEvaluationNum(bossEvaluationNum);
        res.setTaskFit(getScoreString(bossMetrics[0]));
        res.setReality(getScoreString(bossMetrics[1]));
        res.setDefectImportance(getScoreString(bossMetrics[2]));
        res.setRecurrence(getScoreString(bossMetrics[3]));
        res.setTotalQuality(getScoreString(bossMetrics[4]));
        res.setWorkerEvaluationNum(workerEvaluationNum);
        res.setWorkerEvaluationScore(workerEvaluationScore);
        res.setWorkerScores(workerScores);
        res.setCommentWordFreq(commentWordFreq);
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取被评价能力成功！",res);
    }


    //TODO 返回userId写的每一篇评价的平均查重度
    public Double getPlagiarismScore(Integer userId){
        List<Score> scores = scoreMapper.selectByWorker(userId);
        if(scores == null)
            return 0.0;
        System.out.println(scores.size());
        Double plagiarism = 0.0;
        Integer num = 0;
        for(Score score: scores){
            Integer firstId = score.getId();
            List<ScoreSimilarity> similarities = scoreSimilarityMapper.selectByFirstId(firstId);
            for(ScoreSimilarity scoreSimilarity: similarities){
                System.out.println(scoreSimilarity.getSimilarity());
                plagiarism += scoreSimilarity.getSimilarity();
                num ++;
            }
        }
        if(num == 0)
            return 1.0;
        Double res=plagiarism / num.doubleValue();
        if(res>1)
            res=1.0;
        return 1.0-res;
    }

    @Override
    public ResultVO<List<ReportWithWorkerNameVO>> getRecommendReports(Integer userId) {
        List<ReportWithWorkerNameVO>res=new ArrayList<>();
        List<Follow> follows=followMapper.selectByFirstId(userId);
        HashMap<Integer,Boolean> mp=new HashMap<>();
        for(Follow follow:follows){
            Integer id=follow.getFollowingId();
            mp.put(id,true);
            List<Report> reports=reportMapper.selectByUser(id);
            for(Report report:reports){
                ReportVO temp = new ReportVO(report);
                Integer workerid = report.getUserId();
                Integer taskId=report.getTaskId();
                if(taskId==null)
                    continue;
                Task task=taskMapper.selectByPrimaryKey(taskId);
                temp.setWorkername(userMapper.selectByPrimaryKey(workerid).getUsername());
                temp.setTaskname(task.getTaskName());
                temp.setType(task.getType());
                ReportWithWorkerNameVO reportWithWorkerNameVO = new ReportWithWorkerNameVO(temp,workerid);
                res.add(reportWithWorkerNameVO);
            }
        }
//        follows=followMapper.selectBySecondId(userId);
//        for(Follow follow:follows){
//            Integer id=follow.getFollowingId();
//            if(mp.containsKey(id))
//                continue;
//            List<Report> reports=reportMapper.selectByUser(id);
//            for(Report report:reports){
//                ReportVO temp = new ReportVO(report);
//                Integer workerid = report.getUserId();
//                Integer taskId=report.getTaskId();
//                if(taskId==null)
//                    continue;
//                Task task=taskMapper.selectByPrimaryKey(taskId);
//                temp.setWorkername(userMapper.selectByPrimaryKey(workerid).getUsername());
//                temp.setTaskname(task.getTaskName());
//                temp.setType(task.getType());
//                ReportWithWorkerNameVO reportWithWorkerNameVO = new ReportWithWorkerNameVO(temp,workerid);
//                res.add(reportWithWorkerNameVO);
//            }
//        }
        if(res.size() == 0){
            List<Report> reports = reportMapper.selectByUser(userId);
            for(Report report:reports){
                ReportVO temp = new ReportVO(report);
                Integer workerid = report.getUserId();
                Integer taskId=report.getTaskId();
                if(taskId==null)
                    continue;
                Task task=taskMapper.selectByPrimaryKey(taskId);
                temp.setWorkername(userMapper.selectByPrimaryKey(workerid).getUsername());
                temp.setTaskname(task.getTaskName());
                temp.setType(task.getType());
                ReportWithWorkerNameVO reportWithWorkerNameVO = new ReportWithWorkerNameVO(temp,workerid);
                res.add(reportWithWorkerNameVO);
            }
        }
        if(res.size()==0){
            List<Report> reports=reportMapper.selectAll();
            for(Report report:reports){
                ReportVO temp = new ReportVO(report);
                Integer workerid = report.getUserId();
                Integer taskId=report.getTaskId();
                if(taskId==null)
                    continue;
                Task task=taskMapper.selectByPrimaryKey(taskId);
                temp.setWorkername(userMapper.selectByPrimaryKey(workerid).getUsername());
                temp.setTaskname(task.getTaskName());
                temp.setType(task.getType());
                ReportWithWorkerNameVO reportWithWorkerNameVO = new ReportWithWorkerNameVO(temp,workerid);
                res.add(reportWithWorkerNameVO);
            }
        }
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取用户评价综合能力数据成功！",res);

    }
    private Float getScoreFloat(String score){
        switch (score){
            case "低":
                return 0.5F;
            case "偏低":
                return 1.5F;
            case "中":
                return 2.5F;
            case "偏高":
                return 3.5F;
            case "高":
                return 4.5F;
        }
        return Float.valueOf(0);
    }
    private String getScoreString(Float score){
        if(score>0&&score<=1)
            return "低";
        else if(score>1&&score<=2)
            return "偏低";
        else if(score>2&&score<=3)
            return "中";
        else if(score>3&&score<=4)
            return "偏高";
        else if(score>4&&score<=5)
            return "高";
        return "";
    }

}
